package org.apache.tapestry5.csrfprotection.victimapp.pages;

import java.util.ArrayList;
import java.util.List;

import org.apache.tapestry5.ajax.MultiZoneUpdate;
import org.apache.tapestry5.annotations.InjectComponent;
import org.apache.tapestry5.annotations.InjectPage;
import org.apache.tapestry5.annotations.PageAttached;
import org.apache.tapestry5.annotations.Persist;
import org.apache.tapestry5.annotations.Property;
import org.apache.tapestry5.annotations.SessionState;
import org.apache.tapestry5.corelib.components.Form;
import org.apache.tapestry5.corelib.components.Zone;
import org.apache.tapestry5.csrfprotection.CsrfProtected;
import org.apache.tapestry5.ioc.annotations.Inject;
import org.apache.tapestry5.services.Request;
import org.slf4j.Logger;

import util.AuthenticationState;

public class Message {
	private static final String[] CONVERSATION = new String[]{"Hello", "Yes", "How are you?", "I'm fine too", "Yes"};
	
	@Persist
	@Property
	private Integer msgCount;
	
	@InjectPage
	private Index home;
	
	@Persist
	@Property
	private List<String> chat;
	
	@SessionState
	private AuthenticationState auth;
	
	@Property
	private String message;
	
	@InjectComponent
	private Zone chatZone;
	
	@InjectComponent
	private Zone countZone;
	
	@InjectComponent
	private Form messageForm;
		
	private Object onActivate(){
		if(!auth.isLoggedIn()){
			return home;
		}
		return null;
	}
	
	@Inject
	private Request request;
	
	@Inject 
	private Logger logger;
	
	@InjectComponent
	private Zone formZone;
	
	private Object onSuccess(){
		logger.debug("Ajax: " + request.isXHR());		
		chat.add("Me: " + message);
		if(msgCount > CONVERSATION.length -1){
			chat.add("Mr. Turing: " + CONVERSATION[CONVERSATION.length-1]);
		}
		else{
			chat.add("Mr. Turing: " + CONVERSATION[msgCount]);
		}
		msgCount++;
		message = "";
		if(request.isXHR()){		
			return new MultiZoneUpdate("chatZone", chatZone).add("countZone", countZone).add("formZone",formZone);
		}
		return this;
	}
	
	@PageAttached
	private void init(){
		if(chat == null){
			msgCount = 0;
			chat = new ArrayList<String>();
		}
	}
}
